package com.example.api.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Create with Intellij idea
 * User:鲁智明
 * Date:2018/11/18
 * Time:10:33
 *  纯手写Ribbon本地负载均衡的效果
 */
@RestController
public class ExtRibbonController {


    //获取注册中心上的服务列表
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;

    //接口请求总数
    int reqCount=0;

    @RequestMapping("/ribbonMember")
    public String ribbonMember(String name){
        //1.获取api-member 服务远程调用地址
        String instanceUrl=getInstance()+"/getMember";
        //2.可以直接使用httpClient进行调用，使用Rest方式进行调用
        String result = restTemplate.getForObject(instanceUrl, String.class);
        return result;
    }

    //负载均衡算法
    public String getInstance(){
        List<ServiceInstance> instances = discoveryClient.getInstances("api-member");
        if (instances==null||instances.size()<=0){
            return null;
        }
        //获取集群总数
        int instanceSize=instances.size();
        // 取余
        int size=reqCount%instanceSize;
        reqCount++;
        return instances.get(size).getUri().toString();
    }

}
